<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\model\Product\Product as ProductModel;
use app\common\model\Product\Type as TypeModel;
use app\common\model\Product\Vip as VipModel;
use app\common\validate\Product\Product as ProductValidate;
use Exception;
use think\exception\ValidateException;

class Product extends BaseController
{
    protected $middleware = [
        \app\admin\middleware\LoginAuth::class
    ];
    // 商品列表
    public function index()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '商品列表'
        ];
        $searchfield = $this->request->param('search_field', 'product.name');
        $keyword = $this->request->param('keyword');
        // halt($param);
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "%$keyword%"];
        }
        // 每页显示数量
        $num = 8;
        $ProductList = ProductModel::withJoin(['type'])->where($where)->order('id', 'desc')->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $ProductList->currentPage();
        return view('', [
            'menu' => $menu,
            'ProductList' => $ProductList,
            'num' => $num,
            'page' => $page,
            'searchfield' => $searchfield,
            'keyword' => $keyword
        ]);
    }
    // 商品新增
    public function add()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '新增商品'
        ];
        $TypeList = TypeModel::select();
        if ($this->request->isPost()) {
            try {
                $params = $this->request->param();
                $data = [
                    'name' => $params['name'],
                    'typeid' => $params['typeid'],
                    'price' => $params['price'],
                    'stock' => $params['stock'],
                    'content' => $params['content'],
                    'flag' => $params['flag'],
                ];
                if (isset($_FILES['coverArr']) && $_FILES['coverArr']['size'] > 0) {
                    $cover = uploads('coverArr');
                    if ($cover['code'] === 0) {
                        $this->error($cover['msg']);
                    }
                    $data['thumbs'] = json_encode($cover['data']);
                    $data['thumbs'] = str_replace('\\', '', $data['thumbs']);
                }
                validate(ProductValidate::class)->check($data);
                $ProductModel = new ProductModel();
                $ProductStatus = $ProductModel->save($data);
                if ($ProductStatus !== true) {
                    throw new \Exception('新增商品失败');
                }
            } catch (ValidateException $e) {
                $this->error($e->getError());
            } catch (\Exception $error) {
                $this->error($error->getMessage());
            }
            $this->success('新增商品成功', (string)url('admin/product/index'));
        }
        return view('', [
            'menu' => $menu,
            'TypeList' => $TypeList,
        ]);
    }
    // 商品删除
    public function del()
    {
        $action = $this->request->param('action');
        $proid = $this->request->param('proid');
        $ids = $this->request->param('ids');
        try {
            ProductModel::startTrans();
            VipModel::startTrans();
            // 单条软删除
            if ($action == 'Del') {
                $Product = ProductModel::find($proid);
                if (!$Product) {
                    throw new Exception('商品不存在');
                }
                $result = ProductModel::destroy($proid);
                if ($result === false) {
                    throw new Exception('商品删除失败');
                }
                $VipList = VipModel::where(['proid' => $proid])->select();
                foreach ($VipList as $key => $item) {
                    $res = VipModel::destroy($item['id']);
                    if ($res === FALSE) {
                        throw new Exception('删除VIP价格失败');
                    }
                }
            }
            // 批量软删除
            if ($action == 'BatchDelete') {
                $ProductList = ProductModel::whereIn('id', $ids)->select();
                foreach ($ProductList as $key => $item) {
                    if (!in_array($item['id'], $ids)) {
                        throw new Exception("所选商品{$item['name']}不存在,请重新选择");
                    }
                }
                $result = ProductModel::destroy(['id' => $ids]);
                if ($result === false) {
                    throw new Exception('商品删除失败');
                }
                $VipList = VipModel::whereIn('proid', $ids)->select();
                foreach ($VipList as $key => $item) {
                    $res = VipModel::destroy($item['id']);
                    if ($res === FALSE) {
                        throw new Exception('删除VIP价格失败');
                    }
                }
            }
            //单条真实删除
            if ($action == 'del') {
                $Product = ProductModel::onlyTrashed()->find($proid);
                if (!$Product) {
                    throw new Exception('商品不存在');
                }
                $result = ProductModel::destroy($proid, true);
                if ($result === false) {
                    throw new Exception('删除失败');
                } else {
                    $Product['thumbs'] = json_decode($Product['thumbs'], true);
                    foreach ($Product['thumbs'] as $key => $item) {
                        @is_file((string)$item) && unlink($item);
                    }
                }
                $VipList = VipModel::where(['proid' => $proid])->select();
                foreach ($VipList as $key => $item) {
                    $res = VipModel::destroy($item['id'], true);
                    if ($res === FALSE) {
                        throw new Exception('删除VIP价格失败');
                    }
                }
            }
            // 批量真实删除
            if ($action == 'dels') {
                // 查询选中的数据 开启软删除后普通查询不出软删除字段数据 onlyTrashed=>仅查询软删除数据 withTrashed=>所有数据可查
                $ProductList = ProductModel::onlyTrashed()->whereIn('id', $ids)->select();
                foreach ($ProductList as $item) {
                    if (!in_array($item['id'], $ids)) {
                        throw new Exception("所选商品{$item['username']}不存在,请重新选择");
                    }
                }
                $result = ProductModel::destroy($ids, true);

                if ($result !== FALSE) {
                    foreach ($ProductList as $item) {
                        $item['thumbs'] = json_decode($item['thumbs'], true);
                        foreach ($item['thumbs'] as $key => $value) {
                            @is_file((string)$value) && unlink($value);
                        }
                    }
                } else {
                    throw new Exception("批量删除失败");
                }
                $VipList = VipModel::whereIn('proid', $ids)->select();
                foreach ($VipList as $key => $item) {
                    $res = VipModel::destroy($item['id'], true);
                    if ($res === FALSE) {
                        throw new Exception('删除VIP价格失败');
                    }
                }
            }
        } catch (Exception $error) {
            ProductModel::rollback();
            VipModel::rollback();
            $this->error($error->getMessage());
        }
        ProductModel::commit();
        VipModel::commit();
        $this->success('商品删除成功');
    }
    // 商品编辑
    public function edit()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '编辑商品'
        ];
        $proid = $this->request->param('proid');
        $TypeList = TypeModel::select();
        $Product = ProductModel::with('type')->find($proid);
        if (!$Product) {
            $this->error('商品不存在');
        }
        // $Product['thumbs']=>["upload/20220909/1.jpg","upload/20220909/2.jpg"]
        // json_decode($Product['thumbs'], true)=>[
        // 0 => "upload/20220909/1.jpg"
        // 1 => "upload/20220909/2.jpg"
        // ]
        if (isset($Product['thumbs'])) {
            $Product['thumbs'] = json_decode($Product['thumbs'], true);
        }
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $data = [
                'name' => $params['name'],
                'typeid' => $params['typeid'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'content' => $params['content'],
                'flag' => $params['flag'],
            ];
            if (isset($_FILES['coverArr']) && $_FILES['coverArr']['size'] > 0) {
                // 上传图片
                $cover = uploads('coverArr');
                if ($cover['code'] === 0) {
                    $this->error($cover['msg']);
                }
                $data['thumbs'] = json_encode($cover['data']);
                $data['thumbs'] = str_replace('\\', '', $data['thumbs']);
            }
            try {
                validate(ProductValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }
            $ProductStatus = ProductModel::update($data, ['id' => $proid]);
            if ($ProductStatus === false) {
                if (isset($_FILES['coverArr']) || $_FILES['coverArr']['size'] > 0) {
                    foreach ($cover['data'] as $key => $item) {
                        @is_file((string)$item) && unlink($item);
                    }
                }
                $this->error('修改商品失败');
            } else {
                if (isset($_FILES['coverArr']) || $_FILES['coverArr']['size'] > 0) {
                    foreach ($Product['thumbs'] as $key => $item) {
                        @is_file((string)$item) && unlink($item);
                    }
                }
                $this->success('修改商品成功', (string)url('admin/product/index'));
            }
        }

        return view('', [
            'menu' => $menu,
            'TypeList' => $TypeList,
            'Product' => $Product
        ]);
    }
    // 商品回收站
    public function recycle()
    {
        $menu = [
            'name' => '商品管理',
            'title' => '商品回收站'
        ];
        $searchfield = $this->request->param('search_field', 'product.name');
        $keyword = $this->request->param('keyword');
        // halt($param);
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "%$keyword%"];
        }
        // 每页显示数量
        $num = 8;
        $ProductList = ProductModel::onlyTrashed()->withJoin(['type'])->where($where)->order('id', 'desc')->paginate(['list_rows' => $num, 'query' => request()->param()]);
        // 当前页
        $page = $ProductList->currentPage();
        if ($this->request->isPost()) {
            $action = $this->request->param('action');
            $proid = $this->request->param('proid');
            $ids = $this->request->param('ids');
            // halt($proid);
            // 单条恢复
            if ($action == 'recovery') {
                $Product = ProductModel::withTrashed()->find($proid);
                if (!$Product) {
                    $this->error('商品不存在');
                }
                $result = $Product->restore();
                if ($result) {
                    $this->success('恢复成功');
                } else {
                    $this->error('恢复失败');
                }
            }
            // 批量恢复
            if ($action == 'recoverys') {
                // 查询选中的数据
                $ProductList = ProductModel::withTrashed()->whereIn('id', $ids)->select();
                foreach ($ProductList as $item) {
                    if (!in_array($item['id'], $ids)) {
                        $this->error("所选商品{$item['name']}不存在,请重新选择");
                    }
                }
                $result = ProductModel::onlyTrashed()->where(['id' => $ids])->update(['deletetime' => null]);

                if ($result !== FALSE) {
                    $this->success('批量恢复成功');
                } else {
                    $this->error("批量恢复失败");
                }
            }
        }
        return view('', [
            'menu' => $menu,
            'ProductList' => $ProductList,
            'num' => $num,
            'page' => $page,
            'searchfield' => $searchfield,
            'keyword' => $keyword
        ]);
    }
}
